package tcp_listener

import "fmt"
import "net"
import "os"
import "bufio"
import "time"

var username string = ""
var password string = ""
var connection_string string = ""
var conn *net.TCPConn 
var local_address *net.TCPAddr
var remote_address *net.TCPAddr
var buf = make ([]byte, 2048)
func New(uname string, pword string, conn string) {
	username = uname
	password = pword
	connection_string = conn
	Dial()
}

func Dial(){
   	var err os.Error
	var est os.Error
	var eee os.Error
	remote_address, est = net.ResolveTCPAddr(connection_string)
	if(est != nil){
		fmt.Println(est)
		fmt.Println("Remote Address Resolution Failed")
	}
	local_address, eee = net.ResolveTCPAddr(":7070")
	if(eee != nil){
		fmt.Println(eee)
		fmt.Println("Local Address Resolution Failed")
	} 
	fmt.Println("Dialing")
	conn, err = net.DialTCP("tcp", local_address , remote_address)
		if(err != nil){
		fmt.Println(err)
		fmt.Println("Dialing failed")
	}	
	go Read()
	Send()
	time.Sleep(1e9)
}

func Send(){
	var connect string = "CONNECT\nlogin:guest\npasscode:guest\n\n\x00"
	conn.Write([]byte(connect))
	//conn.Write([]byte("login:"))
	//conn.Write([]byte("passcode:"))
	//conn.Write([]byte(""))
	//conn.Write([]byte("^@"))
	var subscribe string = "SUBSCRIBE\ndestination:/queue/example.A\nack: client\n\n\x00"
	conn.Write([]byte(subscribe))
	//conn.Write([]byte("SUBSCRIBE"))
	//conn.Write([]byte("destination:hello"))
	//conn.Write([]byte("ack: client"))
	//conn.Write([]byte(""))
	//conn.Write([]byte("^@"))
	fmt.Println("Listening for result")
	//var message string = "SEND\ndestination:/queue/example.A\n\nHello Queue F\n\x00"
	//conn.Write([]byte(message))
	//var l, ett = conn.Write([]byte(subscribe))
}

func Read(){
    input := bufio.NewReader(conn)
    fmt.Println("Creating Reader Stream")
      for {
	
	//fmt.Println("Still Reading")
        //Get the next line up to the newline
        line, err := input.ReadString('\n')
	fmt.Println(line)
        if err == os.EOF {
	fmt.Println("Bad")
	return
        }
} 
}
